<template>
  <div class="algorithms">
    <!-- 页面标题和操作 -->
    <div class="algorithms-header">
      <div class="header-left">
        <h1 class="page-title">算法题库</h1>
        <p class="page-subtitle">管理和练习算法题目</p>
      </div>
      <div class="header-right">
        <n-button 
          type="primary" 
          @click="showCreateModal = true"
        >
          <template #icon>
            <n-icon><Plus /></n-icon>
          </template>
          添加题目
        </n-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filters">
      <div class="filter-row">
        <n-input
          v-model:value="searchQuery"
          placeholder="搜索题目标题..."
          clearable
          style="width: 300px"
        >
          <template #prefix>
            <n-icon><Search /></n-icon>
          </template>
        </n-input>
        
        <n-select
          v-model:value="selectedDifficulty"
          placeholder="选择难度"
          clearable
          style="width: 150px"
          :options="difficultyOptions"
        />
        
        <n-button 
          @click="resetFilters"
          quaternary
        >
          重置筛选
        </n-button>
      </div>
    </div>

    <!-- 题目列表 -->
    <div class="algorithms-content">
      <div v-if="algorithmsStore.isLoading" class="loading-state">
        <n-spin size="large" />
      </div>
      
      <div v-else-if="filteredAlgorithms.length === 0" class="empty-state">
        <n-empty description="暂无算法题目">
          <template #extra>
            <n-button 
              type="primary" 
              @click="showCreateModal = true"
            >
              添加第一个题目
            </n-button>
          </template>
        </n-empty>
      </div>
      
      <div v-else class="algorithms-grid">
        <n-card
          v-for="algorithm in filteredAlgorithms"
          :key="algorithm.id"
          class="algorithm-card"
          hoverable
          @click="viewAlgorithm(algorithm.id)"
        >
          <div class="card-header">
            <div class="card-title">{{ algorithm.title }}</div>
            <div class="card-actions">
              <n-tag 
                size="small"
                :type="getDifficultyType(algorithm.difficulty)"
              >
                {{ getDifficultyText(algorithm.difficulty) }}
              </n-tag>
              <n-dropdown 
                :options="getCardMenuOptions(algorithm)"
                @select="handleCardMenuSelect"
                trigger="click"
              >
                <n-button 
                  size="small" 
                  quaternary 
                  circle
                  @click.stop
                >
                  <template #icon>
                    <n-icon><DotsVertical /></n-icon>
                  </template>
                </n-button>
              </n-dropdown>
            </div>
          </div>
          
          <div class="card-description">
            {{ truncateText(algorithm.description, 100) }}
          </div>
          
          <div class="card-footer">
            <div class="card-date">
              <n-icon size="14"><Clock /></n-icon>
              {{ formatDate(algorithm.createdAt, 'YYYY-MM-DD') }}
            </div>
            <div class="card-status">
              <n-icon 
                size="14" 
                :color="'#18a058'"
              >
                <Code />
              </n-icon>
              已解决
            </div>
          </div>
        </n-card>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="algorithmsStore.total > algorithmsStore.pageSize" class="pagination">
      <n-pagination
        v-model:page="currentPage"
        :page-count="Math.ceil(algorithmsStore.total / algorithmsStore.pageSize)"
        :page-size="algorithmsStore.pageSize"
        show-size-picker
        :page-sizes="[10, 20, 50]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>

    <!-- 创建题目模态框 -->
    <n-modal 
      v-model:show="showCreateModal" 
      preset="card" 
      title="添加算法题目" 
      style="width: 600px"
    >
      <n-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-placement="top"
      >
        <n-form-item path="title" label="题目标题">
          <n-input 
            v-model:value="createForm.title" 
            placeholder="请输入题目标题"
          />
        </n-form-item>
        
        <n-form-item path="difficulty" label="难度">
          <n-select
            v-model:value="createForm.difficulty"
            placeholder="选择难度"
            :options="difficultyOptions"
          />
        </n-form-item>
        
        <n-form-item path="description" label="题目描述">
          <n-input 
            v-model:value="createForm.description" 
            type="textarea" 
            placeholder="请输入题目描述或粘贴题目内容"
            :rows="6"
          />
        </n-form-item>
        
        <n-form-item label="题目图片（可选）">
          <n-upload
            :file-list="uploadFileList"
            :max="1"
            list-type="image-card"
            accept="image/*"
            @change="handleUploadChange"
          >
            点击或拖拽上传题目图片
          </n-upload>
        </n-form-item>
      </n-form>
      
      <template #footer>
        <div class="modal-footer">
          <n-button @click="showCreateModal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="algorithmsStore.isLoading"
            @click="handleCreateAlgorithm"
          >
            创建
          </n-button>
        </div>
      </template>
    </n-modal>

    <!-- 编辑题目模态框 -->
    <n-modal 
      v-model:show="showEditModal" 
      preset="card" 
      title="编辑算法题目" 
      style="width: 600px"
    >
      <n-form
        ref="editFormRef"
        :model="editForm"
        :rules="createRules"
        label-placement="top"
      >
        <n-form-item path="title" label="题目标题">
          <n-input 
            v-model:value="editForm.title" 
            placeholder="请输入题目标题"
          />
        </n-form-item>
        
        <n-form-item path="difficulty" label="难度">
          <n-select
            v-model:value="editForm.difficulty"
            placeholder="选择难度"
            :options="difficultyOptions"
          />
        </n-form-item>
        
        <n-form-item path="description" label="题目描述">
          <n-input 
            v-model:value="editForm.description" 
            type="textarea" 
            placeholder="请输入题目描述"
            :rows="6"
          />
        </n-form-item>
      </n-form>
      
      <template #footer>
        <div class="modal-footer">
          <n-button @click="showEditModal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="algorithmsStore.isLoading"
            @click="handleUpdateAlgorithm"
          >
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, h } from 'vue'
import { useRouter } from 'vue-router'
import {
  NButton,
  NIcon,
  NInput,
  NSelect,
  NCard,
  NTag,
  NDropdown,
  NSpin,
  NEmpty,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NUpload,
  useMessage,
  useDialog,
  type FormInst,
  type FormRules,
  type UploadFileInfo
} from 'naive-ui'
import {
  Plus,
  Search,
  Clock,
  Code,
  DotsVertical,
  Edit,
  Trash
} from '@vicons/tabler'
import { useAlgorithmsStore } from '@/stores/algorithms'
import { useCalendarStore } from '@/stores/calendar'
import { formatDate, truncateText, getDifficultyText } from '@/utils'
import type { Algorithm, CreateAlgorithmRequest, UpdateAlgorithmRequest } from '@/types/algorithm'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const algorithmsStore = useAlgorithmsStore()
const calendarStore = useCalendarStore()

// 表单引用
const createFormRef = ref<FormInst | null>(null)
const editFormRef = ref<FormInst | null>(null)

// 筛选和搜索
const searchQuery = ref('')
const selectedDifficulty = ref<string | null>(null)
const currentPage = ref(1)

// 模态框状态
const showCreateModal = ref(false)
const showEditModal = ref(false)

// 表单数据
const createForm = ref<{
  title: string
  difficulty: string
  description: string
}>({
  title: '',
  difficulty: '',
  description: ''
})

const editForm = ref<{
  id?: number
  title: string
  difficulty: string
  description: string
}>({
  title: '',
  difficulty: '',
  description: ''
})

// 上传文件列表
const uploadFileList = ref<UploadFileInfo[]>([])

// 难度选项
const difficultyOptions = [
  { label: '简单', value: 'easy' },
  { label: '中等', value: 'medium' },
  { label: '困难', value: 'hard' }
]

// 表单验证规则
const createRules: FormRules = {
  title: [
    {
      required: true,
      message: '请输入题目标题',
      trigger: ['input', 'blur']
    }
  ],
  difficulty: [
    {
      required: true,
      message: '请选择难度',
      trigger: ['change', 'blur']
    }
  ],
  description: [
    {
      required: true,
      message: '请输入题目描述',
      trigger: ['input', 'blur']
    }
  ]
}

// 计算属性
const filteredAlgorithms = computed(() => {
  let algorithms = algorithmsStore.problems
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    algorithms = algorithms.filter((algorithm: any) => 
      algorithm.title.toLowerCase().includes(query) ||
      algorithm.description.toLowerCase().includes(query)
    )
  }
  
  // 难度过滤
  if (selectedDifficulty.value) {
    algorithms = algorithms.filter((algorithm: any) => 
      algorithm.difficulty === selectedDifficulty.value
    )
  }
  
  return algorithms
})

// 获取难度类型
const getDifficultyType = (difficulty: string): 'default' | 'success' | 'warning' | 'error' | 'primary' | 'info' => {
  const types: Record<string, 'default' | 'success' | 'warning' | 'error' | 'primary' | 'info'> = {
    easy: 'success',
    medium: 'warning',
    hard: 'error'
  }
  return types[difficulty] || 'default'
}

// 获取卡片菜单选项
const getCardMenuOptions = (algorithm: Algorithm) => [
  {
    label: '查看详情',
    key: `view-${algorithm.id}`,
    icon: () => h(NIcon, null, { default: () => h(Code) })
  },
  {
    label: '编辑',
    key: `edit-${algorithm.id}`,
    icon: () => h(NIcon, null, { default: () => h(Edit) })
  },
  {
    label: '删除',
    key: `delete-${algorithm.id}`,
    icon: () => h(NIcon, null, { default: () => h(Trash) })
  }
]

// 处理卡片菜单选择
const handleCardMenuSelect = (key: string) => {
  const [action, idStr] = key.split('-')
  const id = parseInt(idStr)
  
  switch (action) {
    case 'view':
      viewAlgorithm(id)
      break
    case 'edit':
      editAlgorithm(id)
      break
    case 'delete':
      deleteAlgorithm(id)
      break
  }
}

// 查看算法题目
const viewAlgorithm = (id: number) => {
  router.push(`/algorithms/${id}`)
}

// 编辑算法题目
const editAlgorithm = (id: number) => {
  const algorithm = algorithmsStore.problems.find((a: any) => a.id === id)
  if (algorithm) {
    editForm.value = {
      id: Number(algorithm.id),
      title: algorithm.title,
      difficulty: algorithm.difficulty,
      description: algorithm.description
    }
    showEditModal.value = true
  }
}

// 删除算法题目
const deleteAlgorithm = (id: number) => {
  const algorithm = algorithmsStore.problems.find((a: any) => a.id === id)
  if (!algorithm) return
  
  dialog.warning({
    title: '确认删除',
    content: `确定要删除题目「${algorithm.title}」吗？此操作不可恢复。`,
    positiveText: '删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await algorithmsStore.deleteProblem(id)
        message.success('题目删除成功')
      } catch (error) {
        message.error('删除题目失败')
      }
    }
  })
}

// 重置筛选
const resetFilters = () => {
  searchQuery.value = ''
  selectedDifficulty.value = null
  currentPage.value = 1
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadAlgorithms()
}

// 处理页面大小变化
const handlePageSizeChange = (pageSize: number) => {
  algorithmsStore.pageSize = pageSize
  currentPage.value = 1
  loadAlgorithms()
}

// 处理上传变化
const handleUploadChange = (options: { fileList: UploadFileInfo[] }) => {
  uploadFileList.value = options.fileList
}

// 创建算法题目
const handleCreateAlgorithm = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    
    const algorithmData: CreateAlgorithmRequest = {
      title: createForm.value.title,
      difficulty: createForm.value.difficulty as 'easy' | 'medium' | 'hard',
      description: createForm.value.description
    }
    
    await algorithmsStore.createProblem(algorithmData)
    
    showCreateModal.value = false
    message.success('题目创建成功')
    
    // 重置表单
    createForm.value = {
      title: '',
      difficulty: '',
      description: ''
    }
    uploadFileList.value = []
    
    // 记录活动
    await calendarStore.recordActivity({ date: new Date().toISOString().split('T')[0], count: 1 })
  } catch (error) {
    console.error('Create algorithm failed:', error)
  }
}

// 更新算法题目
const handleUpdateAlgorithm = async () => {
  if (!editFormRef.value || !editForm.value.id) return
  
  try {
    await editFormRef.value.validate()
    
    const updateData: UpdateAlgorithmRequest = {
      title: editForm.value.title,
      difficulty: editForm.value.difficulty as 'easy' | 'medium' | 'hard',
      description: editForm.value.description
    }
    
    await algorithmsStore.updateProblem(editForm.value.id, updateData)
    
    showEditModal.value = false
    message.success('题目更新成功')
    
    // 重置表单
    editForm.value = {
      title: '',
      difficulty: '',
      description: ''
    }
  } catch (error) {
    console.error('Update algorithm failed:', error)
  }
}

// 加载算法题目
const loadAlgorithms = async () => {
  try {
    await algorithmsStore.fetchProblems({
      page: algorithmsStore.currentPage,
      limit: algorithmsStore.pageSize,
      search: searchQuery.value || undefined,
      difficulty: selectedDifficulty.value || undefined
    })
  } catch (error) {
    console.error('Failed to load algorithms:', error)
  }
}

// 监听搜索和筛选变化
watch([searchQuery, selectedDifficulty], () => {
  currentPage.value = 1
  loadAlgorithms()
})

// 组件挂载时加载数据
onMounted(() => {
  loadAlgorithms()
})
</script>

<style scoped>
.algorithms {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.algorithms-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.filters {
  margin-bottom: 24px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.algorithms-content {
  margin-bottom: 24px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.algorithms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.algorithm-card {
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.algorithm-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  flex: 1;
  margin-right: 12px;
}

.card-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-description {
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 16px;
  min-height: 48px;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #9ca3af;
}

.card-date,
.card-status {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination {
  display: flex;
  justify-content: center;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .algorithms {
    padding: 16px;
  }
  
  .algorithms-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .algorithms-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-row > * {
    width: 100%;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style>